#pragma once

#include<iostream>
#include<string>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/wait.h>
#include<sys/time.h>
#include<sys/resource.h>
#include"../comm/util.hpp"
#include"../comm/log.hpp"

namespace ns_runner
{
    using namespace ns_util;
    using namespace ns_log;

    class Runner
    {
    public:
        Runner(){}
        
        static void SetProcLimit(int _cpu, int _mem)
        {
            //cpu
            struct rlimit cpu_rlimit;
            cpu_rlimit.rlim_max = RLIM_INFINITY;
            cpu_rlimit.rlim_cur = _cpu;
            setrlimit(RLIMIT_CPU, &cpu_rlimit);

            //mem
            struct rlimit mem_limit;
            mem_limit.rlim_max = RLIM_INFINITY;
            mem_limit.rlim_cur = _mem * 1024;
            setrlimit(RLIMIT_AS, &mem_limit);

        }

        //返回值大于0，表示程序异常，返回值为收到的信号
        //返回值等于0，表示程序执行完毕，结果保存到各个临时文件中
        //返回值小于0，内部错误
        static int Run(const std::string &file_name, int cpu_limit, int mem_limit)
        {
            std::string _stdin = PathUtil::Stdin(file_name);
            std::string _stdout = PathUtil::Stdout(file_name);
            std::string _stderr = PathUtil::Stderr(file_name);

            umask(0);
            int _in_fd = open(_stdin.c_str(), O_CREAT | O_RDONLY, 0644);
            int _out_fd = open(_stdout.c_str(), O_CREAT | O_WRONLY, 0644);
            int _err_fd = open(_stderr.c_str(), O_CREAT | O_RDONLY, 0644);
            
            if(_in_fd < 0 || _out_fd < 0 || _err_fd < 0)
            {
                return(-1);
            }
            pid_t pid = fork();
            if(pid < 0)
            {
                close(_in_fd);
                close(_out_fd);
                close(_err_fd);
                return -2;
            }
            else if(pid == 0)
            {
                dup2(_in_fd, 0);
                dup2(_out_fd, 1);
                dup2(_err_fd, 2);
                SetProcLimit(cpu_limit, mem_limit);
                execl(PathUtil::Exe(file_name).c_str(), PathUtil::Exe(file_name).c_str(), nullptr);
                exit(1);
            }
            else
            {
                close(_in_fd);
                close(_out_fd);
                close(_err_fd);
                int status = 0;
                waitpid(pid, &status, 0);
                return status & 0x7F;
            }

        }

        ~Runner(){}
    };
}